<template>
  <div class="visit-record-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>访问记录管理</span>
        </div>
      </template>
      
      <!-- 查询条件 -->
      <div class="search-container">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="渠道">  
            <el-select 
              v-model="searchForm.channelId" 
              placeholder="请选择渠道" 
              clearable 
              style="width: 180px"
              @change="handleChannelChange"
            >
              <el-option 
                v-for="channel in channelsList" 
                :key="channel.id" 
                :label="channel.name" 
                :value="channel.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="联系人">  
            <el-select 
              v-model="searchForm.issueId" 
              placeholder="请选择联系人" 
              clearable 
              style="width: 180px" 
              :disabled="!searchForm.channelId || filteredContactsList.length === 0"
            >
              <el-option 
                v-for="contact in filteredContactsList" 
                :key="contact.id" 
                :label="contact.name" 
                :value="contact.id"
              />
            </el-select>
          </el-form-item>
          <!-- <el-form-item label="IP地址">
            <el-input
              v-model="searchForm.ip"
              placeholder="请输入IP地址"
              clearable
            />
          </el-form-item> -->
          <!-- <el-form-item label="国家代码">
            <el-input
              v-model="searchForm.countryCode"
              placeholder="请输入国家代码(如CN)"
              clearable
            />
          </el-form-item> -->
          <el-form-item label="访问时间">
            <el-date-picker
              v-model="searchForm.dateRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期时间"
              end-placeholder="结束日期时间"
              value-format="YYYY-MM-DD HH:mm:ss"
               popper-class="custom-date-picker"
               :show-footer="false"
            />
          </el-form-item>
          <el-form-item class="actions-item">
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
            <el-button @click="handleExport">导出数据</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <!-- 数据表格 -->
      <div class="table-container">
        <el-table
          v-loading="loading"
          :data="visitRecords.records"
          style="width: 100%"
          stripe
        >
          <el-table-column prop="id" label="ID" width="100" />
          <el-table-column prop="channelId" label="渠道" width="180" >
            <template #default="scope">
              {{ formatChannelName(scope.row.channelId) }}
            </template>
          </el-table-column>
          <el-table-column 
            prop="issueName" 
            label="联系人名称" 
            width="240" 
          />
          <el-table-column prop="ip" label="IP地址" width="150" />
          <el-table-column prop="countryName" label="国家" width="100" :formatter="formatCountryName" />
          <el-table-column
            prop="createTime"
            label="访问时间"
            width="400"
            :formatter="formatDateTime"
          />
          <el-table-column label="操作" width="140" fixed="right">
            <template #default="{ row }">
              <div class="operation-buttons">
                <el-button
                  type="danger"
                  size="small"
                  :icon="Delete"
                  @click="handleDeleteRecord(row)"
                >删除</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="searchForm.page"
            v-model:page-size="searchForm.pageSize"
            :page-sizes="[50,100,500,1000]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="visitRecords.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete } from '@element-plus/icons-vue'
import { getVisitRecords,getAllRegionTree,getAllIssues,getAllChannels,exportVisitRecordData, deleteVisitRecord  } from '@/api/user.js'

export default {
  name: 'VisitRecord',
  setup() {
    // 状态
    const loading = ref(false)
    const visitRecords = ref({
      records: [],
      total: 0,
      size: 50,
      current: 1,
      pages: 1
    })
    
    // 区域列表 - 新增
    const regionList = ref([])
    // 联系人列表
    const contactsList = ref([])
    // 渠道列表 - 新增
    const channelsList = ref([])
    const selectedChannelIssues = ref([]); // 当前选中渠道的联系人ID列表
     const filteredContactsList = ref([]); // 根据渠道过滤后的联系人列表



    // 查询表单
    const searchForm = reactive({
      issueId: '',
      ip: '',
      countryCode: '',
      channelId: '', 
      dateRange: [],
      page: 1,
      pageSize: 50
    })
    
    // 格式化日期时间
    const formatDateTime = (row, column, cellValue) => {
      if (!cellValue) return ''
      // 将ISO时间格式转换为本地时间格式
      const date = new Date(cellValue)
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      const seconds = String(date.getSeconds()).padStart(2, '0')
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    }
    
    // 格式化国家名称 - 新增
    const formatCountryName = (row, column, cellValue) => {
      if (!cellValue) return ''
      // 查找对应的国家名称
      const region = regionList.value.find(item => item.code === cellValue)
      return region ? region.country : cellValue
    }
     // 格式化联系人名称
    const formatContactName = (row, column, cellValue) => {
      if (!cellValue) return ''
      // 查找对应的联系人名称
      //console.log('contactsList.value:', contactsList.value)
      //console.log('cellValue:', cellValue)
      const contact = contactsList.value.find(item => item.id === cellValue)
      return contact ? contact.name : cellValue
    }

      // 加载区域列表 - 新增
    const loadRegionTree = async () => {
      try {
        const response = await getAllRegionTree()
        if (Array.isArray(response)) {
          regionList.value = response
        } else if (response.code === 0) {
          regionList.value = response.data || []
        }
      } catch (error) {
        //console.error('获取区域列表失败:', error)
        ElMessage.error('获取区域列表失败')
      }
    }
    const formatChannelName = (channelId) => {
      if (!channelId) return '-';
      // 在channelsList中查找对应的渠道对象
      const channel = channelsList.value.find(item => item.id === channelId);
      // 如果找到则返回渠道名称，否则返回原始ID或默认文本
      return channel ? channel.name : `未知渠道(${channelId})`;
    }

    // 加载联系人列表 - 修改为处理新的分页数据格式
const loadContactsList = async () => {
  try {
    const response = await getAllIssues()
    //console.log('联系人列表响应:', response)
    // 根据接口返回格式处理数据
    if (response && response.records && Array.isArray(response.records)) {
      // 新的分页数据格式，使用records字段
      contactsList.value = response.records
      //console.log('设置联系人列表(分页格式):', contactsList.value)
    } else if (response && response.code === 0 && Array.isArray(response.data)) {
      // 兼容旧的成功响应格式
      contactsList.value = response.data
    } else if (Array.isArray(response)) {
      // 兼容直接返回数组的格式
      contactsList.value = response
    } else {
      console.warn('获取联系人列表返回格式异常:', response)
      contactsList.value = []
    }
    // 加载联系人后，如果已选择渠道，需要过滤联系人
    if (searchForm.channelId && selectedChannelIssues.value.length > 0) {
      filterContactsByChannel();
    }
  } catch (error) {
    //console.error('获取联系人列表失败:', error)
    ElMessage.error('获取联系人列表失败')
    contactsList.value = []
  }
}
    // 处理渠道选择变化
    const handleChannelChange = async (channelId) => {
      // 清空联系人选择
      searchForm.issueId = '';
      
      if (channelId) {
        try {
          // 调用API获取对应渠道的联系人数据
          const response = await getAllIssues({ channelId: channelId });
          //console.log('按渠道获取联系人响应:', response);
          
          // 处理API返回的数据
          if (response && response.records && Array.isArray(response.records)) {
            // 使用返回的records作为联系人列表
            filteredContactsList.value = response.records;
            //console.log('设置的联系人列表:', filteredContactsList.value);
          } else {
            console.warn('获取联系人列表返回格式异常:', response);
            filteredContactsList.value = [];
          }
        } catch (error) {
          //console.error('获取联系人列表失败:', error);
          ElMessage.error('获取联系人列表失败');
          filteredContactsList.value = [];
        }
      } else {
        filteredContactsList.value = [];
      }
    };
    

const loadChannelsList = async () => {
      try {
        const response = await getAllChannels()
        //console.log('渠道列表响应:', response)
        // 根据接口返回格式处理数据
        if (response && response.records && Array.isArray(response.records)) {
          // 直接使用response.records作为渠道列表
          channelsList.value = response.records
          //console.log('处理后的渠道列表:', channelsList.value)
        } else if (response && response.code === 0 && Array.isArray(response.data)) {
          // 兼容其他可能的格式
          channelsList.value = response.data
          //console.log('处理后的渠道列表(兼容格式):', channelsList.value)
        } else if (Array.isArray(response)) {
          // 兼容直接返回数组的格式
          channelsList.value = response
          //console.log('处理后的渠道列表(数组格式):', channelsList.value)
        } else {
          console.warn('获取渠道列表返回格式异常:', response)
          channelsList.value = []
        }
      } catch (error) {
        //console.error('获取渠道列表失败:', error)
        ElMessage.error('获取渠道列表失败')
        channelsList.value = []
      }
    }

        // 导出访问记录数据方法 - 根据参考代码重新实现
      const handleExport = async () => {
        let loadingMessage = null
        try {
          // 构建导出参数
          const params = {}
          
          // 添加筛选条件
          if (searchForm.issueId) params.issueId = searchForm.issueId
          if (searchForm.ip) params.ip = searchForm.ip
          if (searchForm.countryCode) params.countryCode = searchForm.countryCode
          if (searchForm.channelId) params.channelId = searchForm.channelId
          if (Array.isArray(searchForm.dateRange) && searchForm.dateRange.length === 2) {
            params.startTime = searchForm.dateRange[0]
            params.endTime = searchForm.dateRange[1]
          }
          
          //console.log('导出参数：', params)
          
          // 显示持续的加载提示，不自动消失
          loadingMessage = ElMessage({
            message: '正在导出数据，请稍候...',
            type: 'info',
            duration: 0, // 设置为0表示不自动消失
            showClose: false // 不显示关闭按钮
          })
          
          // 调用导出API - 注意这里直接使用response而不是response.data
          const response = await exportVisitRecordData(params)
          
          // 关闭加载提示
          if (loadingMessage) {
            loadingMessage.close()
            loadingMessage = null
          }
          
          // 创建下载链接 - 直接使用response创建Blob
          const blob = new Blob([response], {
            type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
          })
          const url = window.URL.createObjectURL(blob)
          
          // 创建下载链接并触发下载
          const link = document.createElement('a')
          link.href = url
          link.download = `访问记录_${new Date().toISOString().slice(0, 10)}.xlsx`
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
          
          // 清理URL对象
          window.URL.revokeObjectURL(url)
          
          // 显示成功消息
          ElMessage.success('导出成功！')
          
        } catch (error) {
          // 关闭加载提示
          if (loadingMessage) {
            loadingMessage.close()
            loadingMessage = null
          }
          
          //console.error('导出失败：', error)
          
          // 根据错误类型显示不同的失败消息
          if (error.code === 'ECONNABORTED') {
            ElMessage.error('导出超时，请稍后重试或联系管理员')
          } else if (error.response) {
            const { status, data } = error.response
            if (status === 404) {
              ElMessage.error('导出接口不存在，请检查API路径')
            } else if (status === 500) {
              ElMessage.error('服务器错误，导出失败')
            } else {
              ElMessage.error(`导出失败：${data?.message || '未知错误'}`)
            }
          } else if (error.request) {
            ElMessage.error('网络连接失败，请检查网络')
          } else {
            ElMessage.error('导出失败，请重试')
          }
        }
      }
 
    // 加载访问记录数据
    const loadVisitRecords = async () => {
      try {
        loading.value = true
        
        // 构建请求参数
        const params = {
          pageNum: searchForm.page,
          pageSize: searchForm.pageSize
        }
        
        // 添加可选参数
        if (searchForm.channelId) params.channelId = searchForm.channelId
        if (searchForm.issueId) params.issueId = searchForm.issueId
        if (searchForm.ip) params.ip = searchForm.ip
        if (searchForm.countryCode) params.countryCode = searchForm.countryCode
        if (Array.isArray(searchForm.dateRange) && searchForm.dateRange.length === 2) {
          params.startTime = searchForm.dateRange[0]
          params.endTime = searchForm.dateRange[1]
        }
        
        const response = await getVisitRecords(params)
        //console.log('访问记录数据响应:', response)
        
        // 根据实际后端响应格式处理数据 - 直接使用返回的数据
        if (response && response.records) {
          visitRecords.value = response
        } else {
          // 如果返回的数据格式不正确，设置为空数据
          visitRecords.value = {
            records: [],
            total: 0,
            size: 50,
            current: 1,
            pages: 1
          }
          ElMessage.error('获取数据失败，返回格式不正确')
        }
      } catch (error) {
        //console.error('获取访问记录失败:', error)
        ElMessage.error('获取数据失败，请重试')
        visitRecords.value = {
          records: [],
          total: 0,
          size: 50,
          current: 1,
          pages: 1
        }
      } finally {
        loading.value = false
      }
    }
    
    // 搜索
    const handleSearch = () => {
      searchForm.page = 1 // 搜索时重置为第一页
      loadVisitRecords()
    }
    
    // 重置
    const handleReset = () => {
      searchForm.issueId = ''
      searchForm.channelId=''
      searchForm.ip = ''
      searchForm.countryCode = ''
      searchForm.channelId = ''
      searchForm.dateRange = []
      searchForm.page = 1
      searchForm.pageSize = 50
      selectedChannelIssues.value = [];
      filteredContactsList.value = [];
      loadVisitRecords()
    }
    
    // 分页处理
    const handleSizeChange = (size) => {
      searchForm.pageSize = size
      loadVisitRecords()
    }
    
    const handleCurrentChange = (current) => {
      searchForm.page = current
      loadVisitRecords()
    }

    const handleDeleteRecord = async (row) => {
      if (!row || !row.id) {
        ElMessage.error('未找到有效的访问记录')
        return
      }
      try {
        await ElMessageBox.confirm(
          `确定要删除访问记录 ID：${row.id} 吗？`,
          '删除确认',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )

        const response = await deleteVisitRecord(row.id)

        if (response && (response.code === 0 || response.code === 200 || response.success)) {
          ElMessage.success(response.message || response.result || '删除成功')
          loadVisitRecords()
        } else {
          ElMessage.error(response?.message || response?.result || '删除失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          //console.error('删除访问记录失败:', error)
          ElMessage.error('删除失败')
        }
      }
    }
     
     // 初始加载数据
     loadRegionTree()
     loadChannelsList()
     loadContactsList()
     loadVisitRecords()
 
     return {
       loading,
       visitRecords,
       searchForm,
       regionList,
       contactsList,
       channelsList,
       filteredContactsList,
       formatDateTime,
       formatCountryName,
       formatContactName,
       loadVisitRecords,
       loadContactsList,
       loadChannelsList,
       handleSearch,
       handleReset,
       handleSizeChange,
       handleCurrentChange,
       handleChannelChange,
       handleExport,
       formatChannelName,
       handleDeleteRecord,
       Delete 
     }
   }
 }
</script>

<style scoped>
.visit-record-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
}

.search-container {
  margin-bottom: 20px;
}

.search-form {
  background: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  display: flex;
  flex-wrap: wrap;
  gap: 12px 20px;
}
.search-form :deep(.el-form-item) {
  margin-bottom: 0;
}
.search-form .actions-item {
  display: flex;
  align-items: center;
  gap: 10px;
}
.search-form .actions-item :deep(.el-form-item__content) {
  display: flex;
  align-items: center;
  gap: 10px;
}
.search-form :deep(.el-input__wrapper) {
  border: 1px solid #dcdfe6 !important;
  border-radius: 6px !important;
  box-shadow: none !important;
  outline: none !important;
}
.search-form :deep(.el-input__wrapper:hover) {
  border-color: #c0c4cc !important;
  box-shadow: none !important;
}
.search-form :deep(.el-input__wrapper.is-focus) {
  border-color: #409eff !important;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1) !important;
}
.search-form :deep(.el-input__inner) {
  border: none !important;
  outline: none !important;
  box-shadow: none !important;
}
.search-form :deep(.el-select) {
  width: 180px;
}

.table-container {
  width: 100%;
}

.operation-buttons {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.pagination-container {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}

 
 
</style>